import { app, BrowserWindow, ipcMain } from 'electron'
import '../renderer/store'
import path from 'path'
const fs = require('fs')
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow() {
  /**
   * Initial window options
   */
  /* mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      webgl: true
    }
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  }); */
  function initLoginWinodw() {
    let loginWindow = new BrowserWindow({
      height: 600,
      width: 800,
      useContentSize: true,
      webPreferences: {
        // devTools: false
      }
    })
    loginWindow.loadURL('https://synconhub.coscoshipping.com/')
    loginWindow.webContents.on("did-finish-load", function () {
      //...
      //这里放注入代码逻辑
      //...
      loginWindow.webContents.executeJavaScript(`
        if(document.cookie.includes('cookiePolicy')) {
          document.querySelector('[name="home_signin"]').click()
        } else {
          document.querySelector('.cookie-button .el-button--primary').click()
        }
      `)
    });
    loginWindow.webContents.on('did-get-response-details', function (event, _status, newUrl, originUrl, httpResponseCode) {
      if (newUrl.includes('/admin/user/login') || newUrl.includes('/admin/user/login')) {
        // console.log(_status, newUrl, originUrl, httpResponseCode, event)
        if (httpResponseCode == 200) { //如果登录成，则把cookie传过来
          setTimeout(() => {
            loginWindow.webContents.executeJavaScript(`
              const electron = require('electron')
              electron.ipcRenderer.send('login-success', document.cookie)
            `)
          }, 1000);
        }
      }
    })
    ipcMain.on('login-success', (event, cookies) => {
      fs.writeFileSync('cookies.txt', cookies)
    })
    loginWindow.on('closed', () => {
      loginWindow = null
    });
  }
  initLoginWinodw()
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
